<?php
class SleekCMS_RecoverPasswordModule extends Module {
	public function run () {
		$form = new Form('recover_password', '', 'post', t('Recover password'), array_merge(User()->asArray(), $_POST));

		$form->addField(array(
			'name'			=> 'email', 
			'type'			=> 'email', 
			'title'			=> t('E-mail'), 
			'placeholder'	=> t('Your e-mail address'), 
			'required'		=> true
		));

		if ($data = $form->isSubmitted()) {
			if ($form->validate()) {
				$user = UsersModel::getByEmail($data['email']);

				if ($user) {
					$newPassword = UsersModel::getRandomPassword();

					$user->setPassword($newPassword);
					$user->save();

					mail(
						$user->getData('email'), 
						t('Your new password'), 
						t('We have reset your password. Your new password is: %0', array($newPassword))
					);

					$form->setMessage(t('A new password has been sent to your e-mail.') . " $newPassword"); # TODO: remove $newPassword later
				}
				else {
					$form->setError(t("There's no user with that e-mail address."));
				}
			}
			else {
				$form->setError(t('Make sure you fill out all the fields properly.'));
			}
		}

		$this->setData('form', $form->asHTML());
	}
}
